package com.ifuncat.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ifuncat.gulimall.common.utils.PageUtils;
import com.ifuncat.gulimall.common.utils.Query;
import com.ifuncat.gulimall.product.dao.BrandDao;
import com.ifuncat.gulimall.product.entity.BrandEntity;
import com.ifuncat.gulimall.product.service.BrandService;
import com.ifuncat.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        if (!params.containsKey("key")) { //无查询条件
            IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), new QueryWrapper<>());
            return new PageUtils(page);
        }

        String key = String.valueOf(params.get("key"));
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<BrandEntity>().eq("brand_id", key).or().like("name", key);

        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        //保证brand在其他表的其他表存储的冗余字段更新
        this.updateById(brand);

        if (StringUtils.isNotBlank(brand.getName())) {
            //同步更新其他关联表中的数据
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
            //todo 同步更新其他表相关字段
        }
    }

}